package com.xiaoshuidi.cloud.module.rooms.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.xiaoshuidi.cloud.framework.common.pojo.CommonResult;
import com.xiaoshuidi.cloud.framework.common.pojo.PageResult;
import com.xiaoshuidi.cloud.module.contract.api.ContractApi;
import com.xiaoshuidi.cloud.module.contract.api.ContractRentOrderApi;
import com.xiaoshuidi.cloud.module.contract.enums.bill.OrderDiscountEnum;
import com.xiaoshuidi.cloud.module.contract.enums.bill.OrderFeeSortTypeEnum;
import com.xiaoshuidi.cloud.module.contract.enums.bill.OrderTypeEnum;
import com.xiaoshuidi.cloud.module.contract.vo.OrderFeesMeterVo;
import com.xiaoshuidi.cloud.module.contract.vo.RentOrderCreateMeterReq;
import com.xiaoshuidi.cloud.module.rooms.enums.DeviceTypeEnum;
import com.xiaoshuidi.cloud.module.rooms.enums.RentStatusEnum;
import com.xiaoshuidi.cloud.module.rooms.mapper.RoomSdiotReadingOrderMapper;
import com.xiaoshuidi.cloud.module.rooms.mapper.RoomSdiotReadingOrderRecordMapper;
import com.xiaoshuidi.cloud.module.rooms.pojo.RoomSdiotReadingOrder;
import com.xiaoshuidi.cloud.module.rooms.pojo.RoomSdiotReadingOrderRecord;
import com.xiaoshuidi.cloud.module.rooms.pojo.RoomStateRecord;
import com.xiaoshuidi.cloud.module.rooms.service.RoomHouseService;
import com.xiaoshuidi.cloud.module.rooms.service.RoomSdiotReadingOrderRecordService;
import com.xiaoshuidi.cloud.module.rooms.service.RoomSdiotReadingOrderService;
import com.xiaoshuidi.cloud.module.rooms.service.RoomStateRecordService;
import com.xiaoshuidi.cloud.module.rooms.vo.RoomHouseRespVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.LocalTime;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class RoomSdiotReadingOrderRecordServiceImpl extends ServiceImpl<RoomSdiotReadingOrderRecordMapper,RoomSdiotReadingOrderRecord> implements RoomSdiotReadingOrderRecordService {

    private final RoomSdiotReadingOrderRecordMapper roomSdiotReadingOrderRecordMapper;

    private final RoomSdiotReadingOrderMapper roomSdiotReadingOrderMapper;

//    private final RoomHouseService roomHouseService;

    private final RoomStateRecordService roomStateRecordService;

    private final ContractRentOrderApi contractRentOrderApi;
    @Override
    public CommonResult<String> saveReadingOrderRecord(List<RoomSdiotReadingOrderRecord> list) {

        if(CollectionUtil.isNotEmpty(list)){
            for (RoomSdiotReadingOrderRecord roomSdiotReadingOrderRecord : list) {
                //向批量抄表单更新最后一条抄表记录
                Long readingOrderId = roomSdiotReadingOrderRecord.getReadingOrderId();
                RoomSdiotReadingOrder roomSdiotReadingOrder = roomSdiotReadingOrderMapper.selectById(readingOrderId);
                roomSdiotReadingOrder.setLastTimeReadingTime(roomSdiotReadingOrderRecord.getCurrentReadingTime());
                roomSdiotReadingOrder.setLastTimeReadingCount(roomSdiotReadingOrderRecord.getCurrentReadingCount());
                roomSdiotReadingOrderMapper.updateById(roomSdiotReadingOrder);
                BigDecimal subtract = roomSdiotReadingOrderRecord.getCurrentReadingCount().subtract(roomSdiotReadingOrderRecord.getLastTimeReadingCount());
                Long billId =null;
                //生成手抄表账单
                Long roomHouseId = roomSdiotReadingOrder.getRoomHouseId();
                RoomStateRecord currentState = roomStateRecordService.getByRoomIdAndIsCurrentState(roomHouseId);
                if (currentState.getState().equals(RentStatusEnum.STAYINGIN.getValue())){
                    LocalDate lastTimeReadingTime = roomSdiotReadingOrderRecord.getLastTimeReadingTime(); //上次抄表时间
                    LocalDate currentReadingTime = roomSdiotReadingOrderRecord.getCurrentReadingTime(); //本次抄表时间
                    LocalDate dueDate = roomSdiotReadingOrderRecord.getDueDate();//应收日期
                    BigDecimal fee = roomSdiotReadingOrderRecord.getFee();//账单金额
                    String feeType = roomSdiotReadingOrderRecord.getFeeType();//费项
                    RentOrderCreateMeterReq rentOrderCreateMeterReq=new RentOrderCreateMeterReq();
                    rentOrderCreateMeterReq.setRoomId(roomHouseId);
                    if(ObjectUtil.isEmpty(lastTimeReadingTime)){
                        lastTimeReadingTime =LocalDate.now();
                    }
                    rentOrderCreateMeterReq.setStartTime(lastTimeReadingTime);
                    rentOrderCreateMeterReq.setEndTime(currentReadingTime);
                    rentOrderCreateMeterReq.setOughtPayTime(dueDate);
                    rentOrderCreateMeterReq.setOrderType(OrderTypeEnum.METER.getCode());

                    List<OrderFeesMeterVo> voList =new ArrayList<>();
                    OrderFeesMeterVo orderFeesMeterVo =new OrderFeesMeterVo();
                    orderFeesMeterVo.setFeeSort(OrderFeeSortTypeEnum.ONCE.getCode());
                    if(feeType.equals(DeviceTypeEnum.HOTWATER_FEE_TYPE.getName())){
                        orderFeesMeterVo.setFeeId(4L);
                    }else if (feeType.equals(DeviceTypeEnum.COLDWATER_FEE_TYPE.getName())){
                        orderFeesMeterVo.setFeeId(5L);
                    }else if (feeType.equals(DeviceTypeEnum.AMMETER_FEE_TYPE.getName())){
                        orderFeesMeterVo.setFeeId(6L);
                    }
                    orderFeesMeterVo.setFeeName(feeType);
                    orderFeesMeterVo.setFeeAmount(fee);
                    orderFeesMeterVo.setPaymentCycle(1);
                    orderFeesMeterVo.setDiscountSort(OrderFeeSortTypeEnum.ONCE.getCode());
                    orderFeesMeterVo.setDiscountOrder(OrderDiscountEnum.FIRST.getCode());
                    orderFeesMeterVo.setDiscountType(OrderDiscountEnum.RATE.getCode());
                    voList.add(orderFeesMeterVo);
                    rentOrderCreateMeterReq.setOrderFeesVo(voList);
                    billId = contractRentOrderApi.createOrder(rentOrderCreateMeterReq).getData();
                }
                //向批量抄表记录插入数据
                roomSdiotReadingOrderRecord.setReading(subtract);
                roomSdiotReadingOrderRecord.setBillId(billId);
                roomSdiotReadingOrderRecordMapper.insert(roomSdiotReadingOrderRecord);
            }
        }
        return CommonResult.success("抄表记录已保存");
    }

    @Override
    public PageResult<RoomSdiotReadingOrderRecord> getRecord(Integer pageSize, Integer pageNum,Long readingOrderId) {
        PageHelper.startPage(pageNum,pageSize);
        QueryWrapper<RoomSdiotReadingOrderRecord> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("reading_order_id",readingOrderId).orderByDesc("current_reading_time");
        List<RoomSdiotReadingOrderRecord> roomSdiotReadingOrderRecords = roomSdiotReadingOrderRecordMapper.selectList(queryWrapper);
        PageResult<RoomSdiotReadingOrderRecord> pageResult=new PageResult<>();
        pageResult.setTotal((long) roomSdiotReadingOrderRecords.size());
        pageResult.setList(roomSdiotReadingOrderRecords);
        return pageResult;
    }

    @Override
    public List<RoomSdiotReadingOrder> getreadingOrderByRoomId(Long roomHouseId,List<String> feeType) {
        List<RoomSdiotReadingOrder> roomSdiotReadingOrders=null;
        StringBuffer feeTypestr =new StringBuffer("");
        for(String str:feeType){
            feeTypestr.append("'"+str+"',");
        }
        if(feeTypestr.length()>1){
            roomSdiotReadingOrders = roomSdiotReadingOrderMapper.getreadingOrderByRoomId(roomHouseId, feeTypestr.substring(0, feeTypestr.length() - 1));
        }else{
            roomSdiotReadingOrders = roomSdiotReadingOrderMapper.getreadingOrderByRoomId(roomHouseId,"''");
        }
        return roomSdiotReadingOrders;
    }

    @Override
    public RoomSdiotReadingOrderRecord getRoomSdiotReadingOrderRecord(Long orderId) {
        QueryWrapper<RoomSdiotReadingOrderRecord> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("reading_order_id",orderId)
                .orderByDesc("current_reading_time")
                .last("limit 1");
        return getOne(queryWrapper);
    }


}
